/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.box.storage.indexed.rhino

import org.apache.commons.lang3.SerializationUtils
import org.mozilla.javascript.Context
import org.mozilla.javascript.Function
import org.slf4j.LoggerFactory

class JsRhinoScript {
	val static LOG = LoggerFactory.getLogger(JsRhinoScript)
	val cx = Context.enter();
	val scope = cx.initStandardObjects();
	String json2 = "/META-INF/json2.min.js";

	new() {
		/*var json2File = ClassLoader.getSystemResources(json2);
		while (json2File.hasMoreElements) {
			var strs = IOUtils.toString(json2File.nextElement.openStream, "UTF-8");
			println("aaaaaaa");
			// ScriptableObject.putProperty(scope, "out", Context.javaToJS(System.out, scope))
			cx.evaluateString(scope, strs, null, 1, null);
		}*/
	/*try(var scriptInput = Thread.currentThread.contextClassLoader.getSystemResources(
	 * 	"cool/taomu/rhino/json2.min.js")) {
	 * 	ScriptableObject.putProperty(scope, "out", Context.javaToJS(System.out, scope))
	 * 	cx.evaluateString(scope, IOUtils.toString(scriptInput, "UTF-8"), null, 1, null);
	 }*/
	}

	new(String path) {
		/*this();
		LOG.info(String.format("加载脚本:%s", path))
		try(var scriptInput2 = Thread.currentThread.contextClassLoader.getResourceAsStream(path)) {
			if (scriptInput2 === null) {
				try (var scriptInput3 = new FileInputStream(new File(path))) {
					IOUtils.toString(scriptInput3, "UTF-8").loaderScript;
				} catch (FileNotFoundException ex) {
					LOG.info("", ex);
				}
			} else {
				IOUtils.toString(scriptInput2, "UTF-8").loaderScript;
			}
		}*/
	}

	def Object invoke(String name, String value) {
		var func = scope.get(name)
		if (func instanceof Function) {
			var jfunc = func;
			var String inValue = SerializationUtils.clone(value)
			var result = jfunc.call(cx, scope, scope, #[Context.javaToJS(inValue, scope)])
			return result !== null ? Context.jsToJava(result, Object) : null
		} else {
			LOG.info("unkown method : " + name);
			return null;
		}
	}

	def close() throws Exception {
		Context.exit();
	}

	def loaderScript(String coding) {
		cx.evaluateString(scope, coding, null, 2, null);
	}

}
